<template>
    <el-card shadow="never" style=" width: 100%; border-radius: 4px;">
        <!-- 新增机构信息标题 -->
        <div class="search-container">
            <p class="textitem flex-start" style="font-size: 18px; margin-bottom: 16px;" placeholder="请输入关键字">
            <h2>{{ isEdit ? '修改机构信息' : '新增机构信息' }}</h2>
            </p>
        </div>
        <!-- 分割线 -->
        <div class="line" style="border-top: 1px solid #e4e7ed; margin: 0 16px;"></div>

        <!-- 机构信息表单 -->
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" style="padding: 24px;">
            <!-- 第一行：机构编号、机构名称、机构图片 -->
            <div class="form-row">
                <el-form-item label="机构编号" :style="{ opacity: isEdit ? 1 : 0 }">
                    <el-input v-model="formData.organizationId" :disabled="true" class="organization-number"
                        style="width: 200px; height: 40px;margin-right: 40px;" placeholder="请输入" />
                </el-form-item>
                <!-- <el-form-item label="机构编号" style="opacity: 0;">
                    <el-input v-model="formData.organizationId" :disabled="true" class="organization-number"
                        style="width: 200px; height: 40px;margin-right: 40px;" placeholder="请输入" />
                </el-form-item> -->
                <el-form-item label="机构名称" prop="name">
                    <el-input v-model="formData.name" style="width: 200px; height: 40px;" placeholder="请输入" />
                </el-form-item>


                <!-- <el-form-item label="机构图片：" prop="image">
                    import.meta.env.VITE_BASE_URL
                    <el-upload class="avatar-uploader" :action="`${baseURL}/image/upload`" :show-file-list="false"
                        :on-success="handleAvatarSuccess22">
                        <img :src="formData.image" class="avatar" />
                        <el-upload v-model="formData.image" :auto-upload="false"
                            style="display: flex; align-items: center;">
                            <el-button type="text" size="small" style="color: #409eff;">+点击上传</el-button>
                        </el-upload>
                    </el-upload>

                </el-form-item> -->

            </div>

            <div class="form-row">
                <el-form-item label="联系人姓名">
                    <el-input v-model="formData.contacts" style="width: 200px; height: 40px;margin-right: 40px;"
                        placeholder="请输入" />
                </el-form-item>

                <el-form-item label="联系电话">
                    <el-input v-model="formData.phone" style="width: 200px; height: 40px;" placeholder="请输入" />
                </el-form-item>
            </div>

            <div class="form-row">
                <el-form-item label="机构地址" prop="orgAddress">
                    <el-input v-model="formData.address" style="width: 578px; height: 40px;" placeholder="请输入" />
                </el-form-item>
            </div>

            <div class="form-row">
                <el-form-item label="机构介绍">
                    <el-input type="textarea" v-model="formData.intro" :rows="4" style="width: 578px; height: 120px;"
                        placeholder="请输入" />
                </el-form-item>
            </div>
            <div class="line" style="border-top: 1px solid #e4e7ed; margin: 0 16px;"></div>
            <!-- 操作按钮 -->
            <div class="form-row" style="justify-content: flex-start; margin-top: 24px;">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="handleBack" style="margin-left: 12px;">返回</el-button>
            </div>
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElForm, ElMessage, ElButton, ElInput } from 'element-plus';
import { addOrganizationApi, detailOrganizationApi, updateOrganizationApi } from '@/api/organizationManage';
import { useRouter, useRoute } from 'vue-router';
//路由实例
const route = useRoute();
const router = useRouter();
//图标路径--------------------
const baseURL = import.meta.env.VITE_BASE_URL;
// 表单引用
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
// 表单数据
const formData = ref({
    organizationId: '',
    name: '',
    image: 'https://woniumd.oss-cn-hangzhou.aliyuncs.com/web/jianglan/202507101428857.png',
    contacts: '',
    phone: '',
    address: '',
    intro: ''
});

// 表单校验规则
const formRules = ref({
    name: [
        { required: true, message: '请输入机构名称', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入机构地址', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        {
            validator(_: any, value: string) {
                const phoneRegExp = /^1[3456789]\d{9}$/
                return phoneRegExp.test(value);
            },
            message: '手机号格式不正确',
            trigger: 'blur'
        }
    ]
});
//获取机构的ID(从路由传参传)
const organizationId = computed(() => {
    return route.params._id as string
})
//是否为编辑模式
const isEdit = computed(() => !!organizationId.value)

// 页面加载时初始化数据
onMounted(() => {
    if (isEdit.value) {
        // 编辑获取一个机构详情
        detailOrganizationApi({ _id: organizationId.value })
            .then(res => {
                if (res.code === 200) {
                    formData.value = {
                        ...formData.value,
                        ...res.data,
                    };
                }
            })
            .catch(err => {
                console.error('获取机构详情失败:', err);
            });
    } else {
        // 新增模式生成机构ID
        formData.value.organizationId = generateorganizationId()
    }
})
//新增生成的ID号
function generateorganizationId() {
    const timestamp = Date.now()
    return timestamp.toString()
}
// 保存表单
const handleSave = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            // 判断是新增还是修改
            if (isEdit.value) {
                // 调用修改接口
                updateOrganizationApi(formData.value)
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success('机构修改成功');
                            router.push('/data/organization/list');
                        } else {
                            ElMessage.error(res.message || '修改失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.error('修改机构失败:', err);
                        ElMessage.error('网络错误，修改失败');
                    });
            } else {
                // 调用新增接口
                addOrganizationApi(formData.value)
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success('机构新增成功');
                            router.push('/data/organization/list');
                        } else {
                            ElMessage.error(res.message || '新增失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.error('新增机构失败:', err);
                        ElMessage.error('网络错误，新增失败');
                    });
            }
        }
    });
};
// updateOrganizationApi 
//图片上传的方法--------------不删
// const handleAvatarSuccess22: UploadProps['onSuccess'] = (
//     res
// ) => {
//     if (res.code == 200) {
//         formData.value.image = res.data;
//     }
// }

// 返回列表页
const handleBack = () => {
    router.back();
};



</script>

<style scoped lang="scss">
.search-container {
    padding: 20px 0;
    background: #fff;
    border-radius: 4px;
}



.textitem {
    position: relative;
    padding-left: 12px;
    /* 给蓝色小条留出空间 */
}

.flex-start {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.textitem::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 20px;
    background-color: rgba(41, 132, 248, 1);
    border-radius: 8px;
}


.form-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    >.el-form-item {
        margin-right: 0;
        margin-left: 0;


        &:not(:first-child) {
            margin-left: 24px;
        }
    }


    &:last-child {
        margin-bottom: 0;
    }
}

/* 机构编号输入框样式 */
::v-deep .organization-number .el-input__wrapper {
    border: none !important;
    box-shadow: none !important;
    background-color: #ffffff !important;
    color: #000000 !important;
    height: 40px !important;
    line-height: 40px !important;
}


::v-deep .el-upload .el-button {
    padding: 6px 12px;
    font-size: 14px;
    height: 40px;
    line-height: 1;

}


.el-input {
    --el-input-bg-color: #fff;
    --el-input-border-color: #dcdfe6;
    --el-input-hover-border-color: #c0c4cc;
}
</style>